package com.mjf.cjt.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.cjt.domain.PurchaseArrival;
import com.mjf.cjt.domain.PurchaseArrivalItem;
import com.mjf.cjt.mapper.PurchaseArrivalMapper;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.PurchaseArrivalItemService;
import com.mjf.cjt.service.PurchaseArrivalService;
import com.mjf.cjt.vo.PurchaseArrivalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/5/18 23:31
 */
@Service
@Slf4j
public class PurchaseArrivalServiceImpl extends ServiceImpl<PurchaseArrivalMapper, PurchaseArrival> implements PurchaseArrivalService {


    @Autowired
    private AsyncTMService asyncTMService;
    @Autowired
    private PurchaseArrivalItemService purchaseOrderItemService;
//    @Resource
//    private PurchaseArrivalMapper purchaseOrderMapper;
//    @Autowired
//    private TFrebateService tFrebateService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void asyncJHD(String start, String end) {
        List<PurchaseArrivalVO> purchaseArrivalVOS = asyncTMService.asyncJHD(start, end);
        if (CollectionUtils.isEmpty(purchaseArrivalVOS)) {
            return;
        }
        List<PurchaseArrival> purchaseOrders = new ArrayList<>();
        List<PurchaseArrivalItem> items = new ArrayList<>();

        // 根据订单ID分组
        Map<Long, List<PurchaseArrivalVO>> map =
            purchaseArrivalVOS.stream().collect(Collectors.groupingBy(PurchaseArrivalVO::getId));
        for (Map.Entry<Long, List<PurchaseArrivalVO>> entry : map.entrySet()) {
            PurchaseArrival order = new PurchaseArrival();
            order.setId(entry.getKey());
            order.setOrderNumber(entry.getValue().get(0).getCode());
            if (StrUtil.isNotBlank(entry.getValue().get(0).getVoucherdate())) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                order.setOrderDate(LocalDate.parse(entry.getValue().get(0).getVoucherdate().replace("/", "-"),
                    formatter));
            }
            order.setWarehouseId(entry.getValue().get(0).getWarehouse_id());
            order.setWarehouseCode(entry.getValue().get(0).getWarehouse_code());
            order.setWarehouseName(entry.getValue().get(0).getWarehouse_name());
            order.setSupplierId(entry.getValue().get(0).getPartner_id());
            order.setSupplierCode(entry.getValue().get(0).getPartner_code());
            order.setSupplierName(entry.getValue().get(0).getPartner_name());
            purchaseOrders.add(order);
            for (PurchaseArrivalVO purchaseArrivalVO : entry.getValue()) {
                PurchaseArrivalItem item = new PurchaseArrivalItem();
                item.setItemId(purchaseArrivalVO.getDetails_id());
                item.setOrderId(purchaseArrivalVO.getId());
                item.setMaterialCode(purchaseArrivalVO.getDetails_inventory_code());
                item.setMaterialName(purchaseArrivalVO.getDetails_inventory_name());
                item.setQuantity(purchaseArrivalVO.getDetails_quantity());
                item.setUnitPrice(purchaseArrivalVO.getDetails_origdiscountprice());
                item.setTotalAmount(purchaseArrivalVO.getDetails_origdiscountamount());
                item.setUnitCode(purchaseArrivalVO.getDetails_unit_code());
                item.setUnit(purchaseArrivalVO.getDetails_unit_name());
                item.setRebateRate(purchaseArrivalVO.getDetails_inventory_priuserdefdecm1());
//                item.setRebateAmount(purchaseArrivalVO.getDetails_priuserdefdecm2());
                items.add(item);
            }
        }
        saveOrUpdateBatch(purchaseOrders, 500);
        purchaseOrderItemService.saveOrUpdateBatch(items, 500);
//        Map<String, List<PurchaseArrivalVO>> voMap =
//            purchaseArrivalVOS.stream().collect(Collectors.groupingBy(PurchaseArrivalVO::getPartner_code));
//        List<TFrebate> rebates = new ArrayList<>();
//        for (Map.Entry<String, List<PurchaseArrivalVO>> entry : voMap.entrySet()) {
//            TFrebate rebate = new TFrebate();
//            rebate.setSupplierCode(entry.getKey());
//            rebate.setSupplierName(Optional.ofNullable(entry.getValue().get(0)).map(PurchaseArrivalVO::getPartner_name).orElse(""));
//            rebate.setRebate(entry.getValue().stream().map(PurchaseArrivalVO::getDetails_priuserdefdecm2)
//                .filter(ObjectUtil::isNotNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO));
//            rebates.add(rebate);
//        }
//        // 增加更新返点金额回写 20250608
//        try {
//            tFrebateService.updateRebate2(rebates);
//        } catch (Exception e) {
//            log.error("更新返点金额回写失败", e);
//        }

    }
}
